package com.GamersCom.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.GamersCom.db.User;
import com.GamersCom.model.MgrFactory;
import com.GamersCom.model.UserMgr;

/**
 * Servlet implementation class ChangePassword
 */
public class ChangePassword extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		process(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		process(request, response);
	}

	protected void process(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		HttpSession session = request.getSession();
		String nextView;
		// get username from session
		String username = (String) session.getAttribute("username");

		if (username == null) // redirect to the login page
		{
			nextView = "login.jsp";
		}
		else
		{
			// retrieve the value of submit button
			String submit = request.getParameter("submit");

			if (submit == null) // perform GET action
			{
				nextView = "changepassword.jsp";
			}
			else
			// perform POST action
			{
				// retrieve the data from the form view
				String oldPassword = request.getParameter("old_password");
				String newPassword = request.getParameter("new_password");
				String confirmPassword = request
						.getParameter("confirm_password");

				MgrFactory factory = (MgrFactory) this.getServletContext()
						.getAttribute("mgrFactory");
				UserMgr userMgr = factory.getUserMgr();
				// retrieve user record by username and password
				User user = userMgr.getApprovedUser(username, oldPassword);
				// validate the form data
				if (user == null)
				{
					request.setAttribute("msg", "Wrong old password!");
				}
				else
				{
					if (!newPassword.equals(confirmPassword))
					{
						request.setAttribute("msg",
								"new passwords do not match!");
					}
					else
					{
						user.setPassword(newPassword);
						userMgr.updateUser(user);
						request.setAttribute("msg",
								"Your password has been successfully updated!");
					}
				}

				nextView = "changepassword.jsp";
			}
		}

		request.getRequestDispatcher(nextView).forward(request, response);
	}

}
